package net.cctms.zhishu.webAppFramework.utils;

import android.content.Context;
import android.os.Environment;
import android.support.annotation.Nullable;

import com.bumptech.glide.Glide;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by yf on 2017/8/8.
 */
public class FileUtil {

    private static final String TAG = FileUtil.class.getSimpleName();

    /**
     * 获取缓存文件大小
     */
    public static String getCacheFileSize(Context context) {
        Long size = 0L;
        //缓存图片大小
        File file = StorageUtil.getImageDir();
        size += getDirFilesSize(file);

        //glide缓存的图片
        file = Glide.getPhotoCacheDir(context);
        size += getDirFilesSize(file);

        //启动apk大小
        file = StorageUtil.getApkDir();
        size += getDirFilesSize(file);

        //数据库大小
        file = context.getDir("database", Context.MODE_PRIVATE);
//        file = new File("/data/data/" + context.getPackageName() + "/databases");
        size += getDirFilesSize(file);
        //释放内存
        file = null;

        //处理为M为单位
        double doubleSize = (double) size / (double) (1024 * 1024);
        double doubleSize2 = doubleSize;
        int intP = (int) doubleSize2;
        double nP = (doubleSize - intP) * 100;
        int intNP = (int) Math.rint(nP);
        double cacheSize = (intP + (double) intNP / 100.00);
        BigDecimal b = new BigDecimal(cacheSize);
        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1 + "";
    }

    public static long getFileSize(File file) {
        long s = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                s = fis.available();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            Log.d("FileUtil", "get file size:file not exist!");
        }
        return s;
    }

    public static long getDirFilesSize(File file) {

        try {
            long s = 0;
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if(files!=null){
                    for (File f : files) {
                        s += getDirFilesSize(f);
                    }
                }
            } else {
                s = getFileSize(file);
            }
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;

    }



    /**
     * 清除缓存
     */
    /*
    public static void clearCache(Context context) {
        DefaultShared.putString(Constants.KEY_POP_UP, "");
        DefaultShared.putString(Constants.KEY_START_UP, "");
        //清除缓存
        delFolder(Environment.getExternalStorageDirectory()+File.separator+ StorageUtil.mRootDirName+ File.separator+ "image");
        //清除glide缓存
        delFolder(Glide.getPhotoCacheDir(context).getAbsolutePath());
        //清除数据库表数据
        DBAccessor.deleteAllTable();
        //清除更新时间
        ClientUtil.clearInterval();
        //清除关注推荐以及个人资料页缓存
        UserInfoUtil.clearUserCache();
        //清除过往专题缓存

    }
    */

    /**
     * 删除文件
     *
     * @param dir 文件路径
     * @return
     */
    public static boolean deleteFile(String dir) {
        Log.d("FileUtil", "delete File " + "/dir: " + dir);
        File dirFile = new File(dir);
        File[] files = dirFile.listFiles();
        if (files == null) return false;
        for (File f : files) {
            f.deleteOnExit();
        }
        return true;
    }


    //删除文件夹
    //param folderPath 文件夹完整绝对路径

    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        if(tempList!=null){
            for (int i = 0; i < tempList.length; i++) {
                if (path.endsWith(File.separator)) {
                    temp = new File(path + tempList[i]);
                } else {
                    temp = new File(path + File.separator + tempList[i]);
                }
                if (temp.isFile()) {
                    temp.delete();
                }
                if (temp.isDirectory()) {
                    delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                    delFolder(path + "/" + tempList[i]);//再删除空文件夹
                    flag = true;
                }
            }
        }
        return flag;
    }


    @Nullable
    public static String readFile(File file) {
        Log.i("msg","----file1--"+file.getAbsolutePath()+"--");
        String res = null;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
//            res = EncodingUtils.getString(buffer, "UTF-8");
            res = new String(buffer, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;

    }

    public static void writeFileData(String fileName, String message) {
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(fileName);
            byte[] bytes = message.getBytes();
            fout.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /*
    //// TODO: 2018/2/5 zhangmy 
    //若本地没有HTML模板，则加载asset下的
    public static String readArticleTemplate(Context context, String fileName) {
//        String path = StorageUtil.mTempRootDirName+File.separator+"html"+File.separator+fileName;
        String path = ResourcePackageManager.getH5UnzipPath() + File.separator + fileName;
        Log.i("msg","----file--"+path);
        File file = new File(path);
        if(!file.exists()){
            return FileUtil.getFromAssets(context, fileName);
        }
        String htmlTemplate = readFile(file);
        return htmlTemplate;
    }

    public static String readDisPath(Context context, String fileName) {
//        String path=StorageUtil.mTempRootDirName+File.separator+"html"+File.separator+fileName;
        String path = ResourcePackageManager.getH5UnzipPath() + File.separator + fileName;
        File file = new File(path);
        if (!file.exists()) {
            return Constants.ASSETS_ANDROID_DIRECTORY + Constants.ASSETS_DIS_DIRECTORY + "?userOpenid=";
        }
        return "file://"+path+"?userOpenid=";
    }

    public static String readDisContentPath(Context context, String fileName) {
        String path = ResourcePackageManager.getH5UnzipPath() + File.separator + fileName;
        File file = new File(path);
        if (!file.exists()) {
            return Constants.ASSETS_ANDROID_DIRECTORY + Constants.ASSETS_DIS_DIRECTORY + "#/topicContent";
        }
        return "file://" + path + "#/topicContent";
    }

    public static String getFromAssets(Context context, String fileName) {
        String result = "";
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;
        try {
            inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
            bufReader = new BufferedReader(inputReader);
            String line = "";

            while ((line = bufReader.readLine()) != null)
                result += line;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputReader != null) {
                try {
                    inputReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bufReader != null){
                try {
                    bufReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


*/
    /**
     * 根据文件夹判断用户是否是旧版本升级过来的，并根据上次修改的时间判断是否满足条件
     *
     * @return
     */
    public static boolean isUpdateFromOld() {
        String path = StorageUtil.getOldRootDir() + File.separator + "file" + File.separator + "splashs";
        File file = new File(path);
        long time = file.lastModified();
        long deadTime = stringToLong("2015/07/31 23:59:59");
        return file.exists() && time < deadTime;
    }

    public static Date stringToDate(String strTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static long stringToLong(String strTime) {
        Date date = stringToDate(strTime); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = date.getTime(); // date类型转成long类型
            return currentTime;
        }
    }


    /**
     * 图集 -- 创建文件
     *
     * @param saveName
     * @return
     */
    public static File createPictrueFile(String saveName) {
        File dir = null;
        File file = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            dir = StorageUtil.getDownloadImageDir();
            if (dir != null) {
                file = new File(dir, saveName);
                if (file.exists()) {
                    file.delete();
                }
                return file;
            }
        }
        return null;
    }

    /**
     * 把oldpath文件中的内容复制到newPath文件中去
     *
     * @param oldPath
     * @param newPath
     */
    public static void copyFile(String oldPath, String newPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                fis = new FileInputStream(oldfile); //读入原文件
                fos = new FileOutputStream(new File(newPath));
                byte[] buffer = new byte[1024];
                while (fis.read(buffer) != -1) {
                    fos.write(buffer);
                }
                fos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
